package com.cheys.webapp.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cheys.webapp.model.Admin;

public class AuthFilter implements Filter{
	
	private String uncheck_uri = "";
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		long starttime = System.currentTimeMillis();
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		boolean ischeck = isCheckUri(req,resp);
		if(ischeck){
			LogUtil.getLogger(getClass()).debug(">>VisitorFilter.........Start");
			LogUtil.getLogger(getClass()).info(">>检查用户是否已经登陆");
			Object obj = req.getSession().getAttribute("admin");
			Admin a = (Admin) obj;
			if(obj == null || !StringUtil.isNotBlank(a.getAdminName())){
				LogUtil.getLogger(getClass()).debug("访问者尚未登陆，请登陆");
				resp.sendRedirect("login.html");
				return;
			}else{
				LogUtil.getLogger(getClass()).debug("访问者已登陆");
			}
			LogUtil.getLogger(getClass()).debug(">>VisitorFilter ......End,cost time:"+(System.currentTimeMillis() - starttime)+"ms");
		}
		chain.doFilter(req, resp);
	}

	private boolean isCheckUri(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String req_path = req.getRequestURI();
		String ctx_path = req.getContextPath();
		String uri = req_path.substring(ctx_path.length());
		if(uncheck_uri.indexOf(uri) > -1){
			return false;
		}else{
			if(uncheck_uri.indexOf(",") > -1 && uncheck_uri.indexOf("*") > -1){
				String[] uncheck_urls = uncheck_uri.split(",");
				for (String un_check_url : uncheck_urls) {
					un_check_url = un_check_url.indexOf("*") > -1 ? un_check_url.substring(0,un_check_url.lastIndexOf("/")) : un_check_url;
					if(uri.indexOf(un_check_url) > -1){
						return false;
					}
				}
			}
		}
		return true;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		if(filterConfig.getInitParameter("uncheckurl") != null){
			String str_uri = filterConfig.getInitParameter("uncheckurl");
			if(StringUtil.isNotBlank(str_uri)){
				uncheck_uri = str_uri;
			}
		}
	}
	

}
